const Controller = require('egg').Controller;
const fs = require('fs');
const fsPromises = fs.promises;
const path = require('path');

class UploadController extends Controller {
  /**
   * {des} upload image
   */
	async upload_files() {
        const createPath = (path) => {
            let nP = '', dP = '', i = 0;
            let dir = path.split('/'), len = dir.length;
            dir.splice(-1, 1);
            nP = dir.join('\\') +'\\';
            dir.splice(0, 1);
            dP = dir.join('/') + '/';
            return [nP, dP];
        };  // 路径转换
        const imgT = ['png', 'jpg', 'jpeg', 'gif', 'mp4'];
        const files = this.ctx.request.file,
            fT = files.mimetype.split('/')[1],  // 文件类型
            fZ = files.size,
            uNm = files.filename;  // 文件大小
        // 文件类型和大小限制
        if(imgT.includes(fT)) {  // 限制文件类型 ['png', 'jpg', 'jpeg', 'gif']
            if(Math.floor(fZ/1024) <= 2048) {  // 限制大小 2MB
                const newFileName = `${uNm}.${fT}`,  // 新文件名
                    dir = createPath(files.destination),  // 存放目录
                    oldPath = files.path,  // 上传的源文件
                    newPath = dir[0] + newFileName,  // 写入文件库的图片
                    dataPath = dir[1] + newFileName;  // 写入数据库的图片
                try {
                    // 检查是否已有头像 循环检查目录
                    for(let i=0,len=imgT.length; i<len; i++) {
                        const oldAva = `${dir[0] + uNm}.${imgT[i]}`;
                        try {
                            fs.accessSync(oldAva, fs.constants.F_OK);
                            fsPromises.unlink(oldAva);
                        }catch(err) {}
                    }
                    fsPromises.rename(oldPath, newPath);  // 文件重命名
                    // 图像地址更新返回
                    this.ctx.status = 200;
                    return this.ctx.body = {
                        s: 1,
                        m: 'ok',
                        d: dataPath
                    }
                }catch(err) {
                    this.ctx.status = 500;
                    return this.ctx.body = {
                        s: 0,
                        m: `Fail~${err}`,
                        d: {}
                    }
                }
            }else {
                return this.ctx.body = {
                    s: 102,
                    m: `Fail~Image大小不合法！`,
                    d: {}
                }
            }
        }else {
            return this.ctx.body = {
                s: 101,
                m: `Fail~Image类型不合法！`,
                d: {}
            }
        }
            // const fileStream = await this.ctx.getFileStream(),
            //     fieldName = fileStream.fieldname,
            //     fileName = fileStream.filename;
                
            // // const dir = path.join(this.config.setting.uploadDir);
            // const writeStream = fs.createWriteStream('app/public/uploads');
            // console.log('218*******',fileStream,fieldName, fileName)
            // const streamToBuffer = stream => {
            //     return new Promise((resolve, reject) => {
            //       const buffers = [];
            //       stream.on('error', reject);
            //       stream.on('data', data => buffers.push(data));
            //       stream.on('end', () => resolve(Buffer.concat(buffers)));
            //     });
            //   };
            //   const buf = await streamToBuffer(fileStream);
            //   console.log('235**********', buf);
            
            // writeStream.write(buf, 'utf-8', () => {
            //     console.log('226************');
                
        // })
        
    }
    /** upload video */
    // async upload_video() {
    //   const files = await this.ctx.request;
    //   // stream parsing
    //   const datagram = files.headers['content-type'].split(';')[1];
    //   const  streamData = datagram.split('=')[1];
    //   console.log('76...........', streamData);
    // }
    /** download file */
    async download_file() {
        const query = this.ctx.body,
            file_path = query.path,
            file_dir = query.dir;
      const filePath = path.resolve('app/public/avatars', '251500399@qq.com.jpeg');
      this.ctx.attachment('251500_avatars.jpeg');
      this.ctx.set('Content-Type', 'application/octet-stream');
      return this.ctx.body = fs.createReadStream(filePath);
    }
}

module.exports = UploadController